// packageG/mycomponent/categorySort/categorySort.js
const app = getApp();
var specsManage = []; // 选择池 用于排序
var optionsId = ""; // 选择后的 规格ID
var optionsMaxCount = 1;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    datas: {
      type: null,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    oneClassInd: 0,
    twoClassInd: 0,
    thrClassInd: 0,
    thrMoreShow: false,
    list: [],
    //init 
    page: 1, // 分页数，当前页数
    isLoadMore: true, // 判断是否要加载更多的标志
    total_page: 1, // 总页数
    activatId: "", // 当前的分类id
    LoadMoreTest: "",

    searchScreen: {},
    carts: [],
    show2: false,
    goodsCartsTotal: [],
    goodsInfo: {},
    scrollTop: 0,
    isclickTap: true,
    refresher: false,
    tapClick:true,
    maxPrice: '',
    imgPath: app.globalData.imgPath,
  },
  lifetimes: {
    attached() {
      let language = wx.getStorageSync("langIndex");
      let listArr = this.data.datas.list.list
      for(let i = 0;i<listArr.length;i++){
        let obj = {id:0,name:'全部',children:[]}
        listArr[i].children.unshift(obj);
      }
      this.setData({
        list: listArr,
        language: language.en
      })
      
      if (this.data.list) {
        this.checkClassId();
        this.updateData();
      }
      
      let yz_basic_info = wx.getStorageSync("yz_basic_info");
      if (yz_basic_info) {
        this.setData({
          globalParameter: yz_basic_info.globalParameter
        })
      }
    },
    ready() {
      const query = this.createSelectorQuery();
      query
        .select(".scrollView")
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          this.setData({
            height_left: res[0].height - 100,
            height_right: res[0].height - 95
          })
        });

    }
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() { 
    },
    hide() { },
    resize() { },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    binddragstart_start(e) {
      let one = this.data.oneClassInd;
      let two = this.data.twoClassInd;
      let thr = this.data.thrClassInd;
      let list = this.data.list;
      let activatId;
      if (list[one].children.length > 0) {
        // 有二级
        if (two == 0 && thr == 0) {
          activatId = this.data.activatId
        }
        console.log(list[one].children[two].children)
        if (list[one].children[two].children.length > 0) {
          console.log('有三级')
          if (thr == 0) {
            console.log('有三级 ---- 三级是第一个，切换二级分类',two)
            if (two == 0) {
              activatId = this.data.activatId;
            } else {
              two = two - 1;
              console.log(list[one].children[two],'二级是全部')
              if(list[one].children[two].id == 0){
                activatId = list[one].id
              }else{
                if(list[one].children[two].children.length >0){
                  activatId = list[one].children[two].children[thr].id
                }else{
                  activatId = list[one].children[two].id;
                }
              }
            }
          } else {
            thr = thr - 1
            activatId = list[one].children[two].children[thr].id
          }
        } else {
          console.log('没三级')
          if (two == 0) {
            console.log('二级已经是第一个')
            activatId = this.data.activatId;
          } else {
            console.log('二级不是第一个，切换二级')
            two = two - 1;
            if (list[one].children[two].children.length > 0) {
              console.log('上一个二级有三级分类')
              thr = 0
              this.setData({
                twoClassInd: two,
                thrClassInd: thr
              })
              activatId = list[one].children[two].children[thr].id;
            }else{
              console.log("上一个二级mei有三级分类");
              if(list[one].children[two].id == 0){
                activatId = list[one].id
              }else{
                activatId = list[one].children[two].id;
              }
            }
          }
        }
      } else {
        console.log('没有二级')
        activatId = this.data.activatId;
      }
      this.setData({
        twoClassInd: two,
        thrClassInd: thr,
        activatId: activatId,
        refresher: false,
        page: 1,
        isLoadMore: true,
        total_page: 1,
        searchScreen: {}
      })
      this.getGoods();
      console.log('binddragstart_start', e)
    },
    bindscrolltolower_end(e) {
      console.log('当前商品列表是否有加载更多', this.data.page, this.data.total_page,this.data.page < this.data.total)
      if (this.data.page < this.data.total_page ) {
        console.log(":sdasdasdasds")
        this.getMore();
        return
      }
      return
      if (!this.data.isclickTap) return
      let one = this.data.oneClassInd;
      let two = this.data.twoClassInd;
      let thr = this.data.thrClassInd;
      let list = this.data.list;
      let activatId;
      if (list[one].children.length > 0) {
        //是否有二级
        console.log('有二级')
        console.log((list[one].children.length - 1), two)
        if ((list[one].children.length - 1) == two) {
          console.log('二级最后一个')
          if (list[one].children[two].children.length > 0) {
            console.log('二级最后一个 ---- 有三级')
            console.log(list[one].children[two].children[thr])
            if ((list[one].children[two].children.length - 1) == thr) {
              console.log('二级最后一个 ---- 有三级 --- 三级最后一个 ---------- 不切换一级')
              // activatId = this.data.activatId;
              this.setData({
                twoClassInd:0,
                thrClassInd:0
              })
              activatId = list[one].id;
              app.tips('没有更多了')
            } else {
              console.log('二级最后一个 ---- 有三级 --- 三级不是最后一个')
              thr = thr + 1;
              this.setData({
                thrClassInd: thr
              })
              console.log(list[one].children[two].children[thr].id)
              activatId = list[one].children[two].children[thr].id;
            }
          } else {
            console.log('二级最后一个 ---- 没三级')
            two = 0;
            this.setData({
              twoClassInd: two
            })
            if (list[one].children[two].children.length > 0) {
              //上一个二级是有三级
              console.log('上一个二级是有三级分类')
              activatId = list[one].children[two].children[thr].id
            } else {
              console.log('上一个二级没有三级分类1')
              if(list[one].children[two].id == 0){
                activatId = list[one].id;
              }else{
                activatId = list[one].children[two].id;
              }
            }
          }
        } else {
          console.log('二级不是最后一个')
          // this.selectThr(list,one,two,thr);
          if (list[one].children[two].children.length > 0) {
            console.log(' 有三级')
            if ((list[one].children[two].children.length - 1) == thr) {
              console.log(' 有三级 --- 三级最后一个 --- 切换二级')
              two = two + 1;
              thr = 0
              if(list[one].children[two].children.length == 0){
                this.setData({
                  twoClassInd: two,
                  thrClassInd: thr
                })
                activatId = list[one].children[two].id;
              }else{
                this.setData({
                  twoClassInd: two,
                  thrClassInd: thr
                })
                activatId = list[one].children[two].children[thr].id;
              }
             
            } else {
              console.log('有三级 --- 三级不是最后一个')
              thr = thr + 1;
              this.setData({
                thrClassInd: thr
              })
              console.log(list[one].children[two].children[thr].id)
              activatId = list[one].children[two].children[thr].id;
            }
          } else {
            console.log(' 没三级')
            two = two + 1;
            this.setData({
              twoClassInd: two
            })
            if (list[one].children[two].children.length > 0) {
              //上一个二级是有三级
              console.log('上一个二级是有三级分类')
              activatId = list[one].children[two].children[thr].id
            } else {
              console.log('上一个二级没有三级分类2')
              if(list[one].children[two].id == 0){
                activatId = list[one].id;
              }else{
                activatId = list[one].children[two].id;
              }
            }
          }
        }
      } else {
        console.log('没二级', this.data.activatId)
        activatId = this.data.activatId;
      }
      // }

      console.log('bindscrolltolower_end', activatId)
      this.setData({
        activatId,
        page: 1,
        isLoadMore: true,
        total_page: 0,
        searchScreen: {}
      });
      this.getGoods();
    },
    init() {
      let sort = this.selectComponent('#sort');
      sort.init();
      this.setData({
        page: 1,
        isLoadMore: true,
        total_page: 1,
        activatId: '',
        searchScreen: {}
      })
    },
    addGood(e) {
      let good = e.target.dataset.item || e.currentTarget.dataset.item;
      console.log(e)
      if(good.has_option != 1){
        this.numberRight(good);
        return
      }
      this.setData({
        show2: true,
        goodsInfo: good,
      });
      this.initPopView(); // 初始化弹窗view
    },
    numberRight(e) {
      console.log(e,'dddddddddd')
      let id = e.id;
      let _stock = e.stock;
      let good = e;
      //价格权限
      if (good.vip_level_status && good.vip_level_status.status == 1) {
        wx.showToast({
          title: good.vip_level_status.tips,
          icon: "none",
          duration: 2000,
        });
        return false;
      }
  
      if (_stock == 0) {
        wx.showToast({
          title: "库存为零",
          icon: "none",
        });
        return;
      }
  
      if (!app._isTextEmpty(this.data.goodsCartsTotal[id])) {
        if (this.data.goodsCartsTotal[id].total >= _stock) {
          console.log("数量超出范围");
          wx.showToast({
            title: "库存不足",
            icon: "none",
          });
          return;
        }
        let obj = this.data.goodsCartsTotal;
        obj = Number(obj[id].total) + 1;
        this.data.goodsCartsTotal[id].total = obj;
      }
      let jsons = {
        goods_id: id,
        total: 1,
      };
      let urlStr = app.getNetAddresss("member.member-cart.store");
      app._getNetWork({
        url: urlStr,
        data: jsons,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            app.globalData.cart_num = app.globalData.cart_num + 1;
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
            this.triggerEvent('AddCartMethod')
            this.updateData();
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        },
      });
    },
    toGood(e) {
      let id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/packageA/detail_v2/detail_v2?id=' + id,
      })
    },
    tapOneClass(e) {
      let ind = e.currentTarget.dataset.ind;
      this.setData({
        oneClassInd: ind,
        twoClassInd: 0,
        thrClassInd: 0,
      })
      this.init();
      this.checkClassId();
    },
    tapTwoClass(e) {
      let ind = e.currentTarget.dataset.ind;
      this.setData({
        twoClassInd: ind,
        thrClassInd: 0,
      })
      this.init();
      this.checkClassId();
    },
    tapThrClass(e) {
      let ind = e.currentTarget.dataset.ind;
      let id = e.currentTarget.dataset.id;
      // this.setData({
      // })
      this.init();
      // this.checkClassId();
      this.setData({
        thrClassInd: ind,
        activatId:id,
        foodInfo: [],
      });
      this.getGoods();
    },
    onChange(event) {
      this.setData({
        activeNames: event.detail,
      });
    },
    showbox(e) {
      console.log(e)
      // 改变筛选框
      this.setData({
        showGoodScreen: !this.data.showGoodScreen
      });
    },
    MoreBoxThrTap(e) {
      this.setData({
        thrMoreShow: !this.data.thrMoreShow
      })
    },
    sortOut(e) {
      this.setData({
        showGoodScreen: false
      });
      this.data.searchScreen.order_field = e.detail.order_field;
      this.setData({
        maxPrice: e.detail.order_field
      })
      this.data.searchScreen.order_by = e.detail.order_by;
      this.checkClassId()
    },
    confirmGoodScreen(e) {
      let arr = e.detail;
      this.setData({
        showGoodScreen: false,
        searchScreen: arr
      })
      this.checkClassId();
    },
    cloneGoodScreen() {
      this.setData({
        showGoodScreen: false
      })
    },
    checkClassId() {
      let one = this.data.oneClassInd;
      let two = this.data.twoClassInd;
      let thr = this.data.thrClassInd;
      let list = this.data.list;
      let activatId;
      if (list[one].children.length > 0) {
        if (list[one].children[two].children.length > 0) {
          activatId = list[one].children[two].children[thr].id;
        } else {
          if(list[one].children[two].id == 0){
            activatId = list[one].id;
          }else{
            activatId = list[one].children[two].id;
          }
        }
      } else {
        activatId = list[one].id;
      }
      console.log(activatId)
      this.setData({
        activatId,
        foodInfo: []
      });
      this.getGoods();
    },
    getMore() {
      wx.showLoading({
        title: '加载更多',
      })
      // 防止多次请求分页数据
      const that = this;
      if (that.data.page >= that.data.total_page) {
        that.setData({
          LoadMoreTest: "没有更多",
        });
        that.setData({
          isLoadMore: false,
        });
        return;
      } else {
        that.setData({
          isLoadMore: true,
        });
        let page = that.data.page;
        page += 1;
        that.setData({
          page,
        });
        let urlStr = app.getNetAddresss("goods.category.get-goods-list-by-category-id");
        let price;
        if (this.data.searchScreen.top || this.data.searchScreen.mini) {
          if (!this.data.searchScreen.mini) {
            price = this.data.searchScreen.top
          } else {
            price = `${this.data.searchScreen.mini}${this.data.searchScreen.top ? ',' + this.data.searchScreen.top : this.data.searchScreen.top ? this.data.searchScreen.top : ''}`
          }
        }
        let jsons = {
          goods_page: that.data.page,
          category_id: that.data.activatId,
          order_field: this.data.searchScreen.order_field || '',
          order_by: this.data.searchScreen.order_by || '',
          "search[brand_id]": this.data.searchScreen.brandId || '',
          "search[product_attr]": this.data.searchScreen.attrstr || '',
          "search[filtering]": this.data.searchScreen.filterId || '',
          "search[price_range]": price || '',
        };
        app._getNetWork({
          url: urlStr,
          data: jsons,
          success: (resdata)=> {
            wx.hideLoading({
              success: (res) => {},
            })
            var res = resdata.data;
            that.setData({
              isLoadMore: true,
            });
            if (res.result == 1) {
              let foodInfo = that.data.foodInfo;
              foodInfo = foodInfo.concat(res.data.data); // 进行数组拼接
              that.setData({
                foodInfo,
              });
            } else {
              let pages = that.data.page;
              pages -= 1;
              that.setData({
                page: pages,
                isLoadMore: false,
              });
              return;
            }
          },
          fail: function (res) {
            wx.hideLoading({
              success: (res) => {},
            })
            console.log(res);
          },
        });
      }
    },
    getGoods() {
      console.log(this.data.scrollTop)
      if (!this.data.isclickTap) return
      this.data.isclickTap = false;
      let that = this;
      let urlStr = app.getNetAddresss("goods.category.get-goods-list-by-category-id");
      let price;
      let one = this.data.oneClassInd;
      let two = this.data.twoClassInd;
      if(this.data.list[one].children[two].children.length > 0){
        const query = this.createSelectorQuery();
        query
          .select(".scrollView")
          .fields({
            node: true,
            size: true
          })
          .exec((res) => {
            this.setData({
              height_right: res[0].height - 200
            })
          });
      }else{
        const query = this.createSelectorQuery();
        query
          .select(".scrollView")
          .fields({
            node: true,
            size: true
          })
          .exec((res) => {
            this.setData({
              height_right: res[0].height - 95
            })
          });
      }
      if (this.data.searchScreen.top || this.data.searchScreen.mini) {
        if (!this.data.searchScreen.mini) {
          price = this.data.searchScreen.top
        } else {
          price = `${this.data.searchScreen.mini}${this.data.searchScreen.top ? ',' + this.data.searchScreen.top : this.data.searchScreen.top ? this.data.searchScreen.top : ''}`
        }
      }
      let jsons = {
        goods_page: that.data.page,
        category_id: that.data.activatId,
        order_field: this.data.searchScreen.order_field || '',
        order_by: this.data.searchScreen.order_by || '',
        "search[brand_id]": this.data.searchScreen.brandId || '',
        "search[product_attr]": this.data.searchScreen.attrstr || '',
        "search[filtering]": this.data.searchScreen.filterId || '',
        "search[price_range]": price || '',
      };
      wx.showLoading({
        title: '商品加载中',
      })
      this.setData({ loading: true })
      app._getNetWork({
        url: urlStr,
        data: jsons,
        success: (resdata) => {
          
          let res = resdata.data;
          if (res.result == 1) {
            this.setData({
              page: 1,
              total_page: res.data.last_page,
              foodInfo: res.data.data,
              scrollTop: 0,
              LoadMoreTest: res.data.last_page == 1 ? "没有更多" : "加载更多"
            });
            // var query = this.createSelectorQuery();
            // setTimeout(() => {
            //   query
            //     .select(".goodsList")
            //     .fields({
            //       node: true,
            //       size: true
            //     })
            //     .exec((res) => {
            //       console.log('ddddddddddd',res[0].height)
            //       that.setData({
            //         height_right_good: this.data.foodInfo.length<3 ?res[0].height+200:res[0].height
            //       })
            //     });
            // }, 1000);
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
          this.setData({
            isLoadMore: true,
            loading: false
          });
          setTimeout(() => {
            wx.hideLoading()
            this.data.isclickTap = true;
          }, 500);
        },
        fail: function (res) {
          wx.hideLoading()
          this.data.isclickTap = true;
        },
      });
    },
    // 弹窗提交确认
    submitAction() {
      let that = this;
      if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
        // 请选择规格
        this.setData({
          show2: false,
        });
        wx.showToast({
          title: this.data.goodsDescription,
          icon: "none",
        });
        return;
      }
      let urlStr = app.getNetAddresss("member.member-cart.store");
      let json = {
        goods_id: this.data.goodsInfo.id,
        total: 1,
        option_id: optionsId,
      };
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            app.globalData.cart_num = res.data.cart_num;
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
            this.triggerEvent('AddCartMethod')
            that.updateData();
            that.setData({
              popNum: that.data.popNum + 1,
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    updateData() {
      // 更新购物车数据
      let urlStr = app.getNetAddresss("member.member-cart.index");
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res.data)
            this.getCart(res.data);
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        },
      });
    },
    destroyData(_cid) {
      // 清除该购物车商品id
      let urlStr = app.getNetAddresss("member.member-cart.destroy");
      let json = {
        ids: _cid,
      };
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          this.data.tapClick = true;
          if (res.result == 1) {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
            app.globalData.cart_num = app.globalData.cart_num - 1;
            this.triggerEvent('AddCartMethod')
            this.updateData();
            this.setData({
              show2: false,
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        },
      });
    },
    changeAddCount(e) {
      // console.log(this.data.tapClick,'changeAddCount')
      if(!this.data.tapClick){
        return
      }
      this.data.tapClick = false;
      let _id = e.target.dataset.id || e.currentTarget.dataset.id;
      let _num = e.target.dataset.num || e.currentTarget.dataset.num;
      let index = e.target.dataset.i || e.currentTarget.dataset.i;
      index = Number(index);
      if (_num <= 0) {
        this.destroyData(_id);
        return;
      }
      let json = {
        id: _id,
        num: _num,
      };
      let urlStr = app.getNetAddresss("member.member-cart.updateNumV2");
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          setTimeout(() => {
            this.data.tapClick = true;
          }, 1000);
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
            if (!app._isTextEmpty(index)) {
              // 规格商品
              let num = this.data.popNum;
              switch (index) {
                case -1:
                  num -= 1;
                  this.setData({
                    popNum: num,
                  });
                  break;
                case 1:
                  num += 1;
                  this.setData({
                    popNum: num,
                  });
                  break;
                default:
                  console.log("error");
              }
            }
            this.triggerEvent('AddCartMethod')
            this.updateData();
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
            this.triggerEvent('AddCartMethod')
            this.updateData();
          }
        },
        fail:(err)=>{
          this.data.tapClick = true;
        }
      });
    },
    getCart(goods) {
      this.setData({
        carts: goods,
        goodsCarts: [],
        cartIDs: [],
      });
      let arrObj = {};
      this.data.carts.forEach((item) => {
        arrObj[item.goods_id] = item;
        if (goods && goods.id == item.goods_id) {
          goods.buyNum = item.total;
        }
        if (item.goods_id == this.data.goodsInfo.id && item.option_id == optionsId) {
          this.setData({
            popNum: item.total,
            popCard: item,
          });
        }
        this.data.cartIDs.push(item.id);
      });
      this.setData({
        goodsCarts: arrObj,
      });

      let goodsCartsTotal = this.calculateTotal(this.data.carts);
      this.setData({
        goodsCartsTotal,
      });
    },
    // 不同规格的同一商品求和
    calculateTotal(arr) {
      let newArr = [];
      let temp = {};
      let newArr2 = {};
      for (let i in arr) {
        let key = arr[i].goods_id;
        if (temp[key]) {
          // temp[key].goods_id = temp[key].goods_id;
          temp[key].total = temp[key].total + arr[i].total;
        } else {
          temp[key] = {};
          temp[key].goods_id = arr[i].goods_id;
          temp[key].total = arr[i].total;
        }
      }
      for (let k in temp) {
        newArr.push(temp[k]);
      }

      newArr.forEach((item) => {
        newArr2[item.goods_id] = item;
      });

      return newArr2;
    },
    // 初始化弹窗view
    initPopView() {
      optionsId = "";
      specsManage = [];
      this.setData({
        specid: "",
        popNum: 0,
      });
      if (this.data.goodsInfo.has_option == 1) {
        // 是否有规格
        this.setData({
          popTitle: this.data.goodsInfo.title,
          popThumb: this.data.goodsInfo.thumb,
          popStock: this.data.goodsInfo.stock,
          popCard: {},
        });
        // 设置默认图片
        // 设置商品名
        // 设置默认库存
        if (!this.data.specid.length) {
          let popPrice = this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price; // 设置默认价格
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.min_point + "-" + this.data.goodsInfo.point_goods.max_point; //设置默认价格
          }
          this.setData({
            popPrice: popPrice,
          });
        }
        this.setData({
          goodsDescription: "请选择",
        });
        let goodsDescription;
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          goodsDescription = this.data.goodsDescription;
          goodsDescription += "" + this.data.goodsInfo.has_many_specs[i].title;
        }
        this.setData({
          goodsDescription,
        });
        if (!this.data.optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
            if (this.data.goodsInfo.goods_option_ids && this.data.goodsInfo.goods_option_ids.length >= 0) {
              for (let j = 0; j < this.data.goodsInfo.has_many_specs[i].has_many_specs_item.length; j++) {
                if (this.data.goodsInfo.has_many_specs[i].has_many_specs_item[j].id == Number(this.data.goodsInfo.goods_option_ids[i])) {
                  this.selectSpecs(this.data.goodsInfo.has_many_specs[i].has_many_specs_item[j], "first", i);
                }
              }
            } else {
              this.selectSpecs(this.data.goodsInfo.has_many_specs[i].has_many_specs_item[0], "first", i);
            }
          }
        }
      } else {
        this.setData({
          goodsDescription: "",
          optionsMaxCount: this.data.goodsInfo.stock,
        });
        // 设置最大购买量
      }
    },
    // 界面选择规格触发事件
    selectSpecs(e, str, i) {
      let data = {};
      let id = 0;

      if (str == "first") {
        data = e;
        id = e.id;
      } else {
        data = e.target.dataset.item || e.currentTarget.dataset.item;

        id = e.target.dataset.id || e.currentTarget.dataset.id;
      }

      // 处理选择池
      this.manageSpecs(data);

      // 处理规格组合选择状态
      this.setGoodsSpecs(data);

      // 设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo(id);

      // 判断当前购买总量与库存的关系
      this.getMaxCount();
    },
    // 处理选择池
    manageSpecs(data) {
      var specsObject = {};
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;

      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      // 排序
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setGoodsDescription();
    },
    // 处理goodsDescription 数据
    setGoodsDescription() {
      var description = "";
      // 相等代表全选了 体现语句
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.setData({
          goodsDescription: description,
        });
      } else {
        description = "请选择 ";

        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
              description += this.data.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.setData({
          goodsDescription: description,
        });
      }
    },
    // 判断当前购买总量与库存的关系
    getMaxCount() {
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          // 库存不足
          this.setData({
            popNum: 0,
          });
        }
        if (this.data.popNum > optionsMaxCount) {
          this.setData({
            popNum: optionsMaxCount,
          });
        }
      }
    },
    // 处理规格组合选择状态 过滤数据
    setGoodsSpecs(specs) {
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
          this.setGoodsSpecsStatus(this.data.goodsInfo.has_many_specs[i].has_many_specs_item, specs.id);
        }
      }
    },
    // 处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
    setGoodsSpecsStatus(specitem, id) {
      let options = []; // 数据池

      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
        // 判断是否包含
        for (let j = 0; j < _specs.length; j++) {
          if (_specs[j] == id) {
            options.push(this.data.goodsInfo.has_many_options[i]);
          }
        }
      }

      for (let m = 0; m < options.length; m++) {
        let _specs = options[m].specs.split("_");
        for (let y = 0; y < _specs.length; y++) {
          if (_specs[y] != id && options[m].stock == 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = true;
              }
            }
          } else if (_specs[y] != id && options[m].stock > 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = false;
              }
            }
          }
        }
      }
    },
    // 处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); // 先变成数组
      // _specs.sort();//排序
      _specs.sort(function (a, b) {
        return a - b;
      });

      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"

      return goodsSpecs;
    },
    // 设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo(id) {
      let popPrice = "";
      // 根据ID 排序 specsManage.sort()
      specsManage.sort(function (a, b) {
        return a.id - b.id;
      });
      if (specsManage.length === this.data.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"
        this.setData({
          specid: goodsSpecs,
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
          if (goodsSpecs === this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
            if (this.data.goodsInfo.point_goods) {
              popPrice = this.data.goodsInfo.point_goods.point_option[i].goods_point; //设置默认价格
            } else {
              popPrice = this.data.goodsInfo.has_many_options[i].product_price; //设置默认价格
            }
            this.setData({
              popPrice: popPrice,
            });
            // 设置默认价格
            // 设置价格
            let popThumb = app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb; // 设置图片
            this.setData({
              popThumb,
              popStock: this.data.goodsInfo.has_many_options[i].stock,
            }); // 设置库存

            optionsId = this.data.goodsInfo.has_many_options[i].id; // 设置规格ID，用于生成订单
            optionsMaxCount = this.data.goodsInfo.has_many_options[i].stock; // 库存最大数 用于切换更改买家购买数量
            if (optionsMaxCount > 0) {
              this.setData({
                popNum: 0,
              });
            }
            if (this.data.isMultiSpecs) this.getMemberPrice(optionsId);
            break;
          }
        }

        for (let i = 0; i < this.data.carts.length; i++) {
          if (this.data.carts[i].goods_id == this.data.goodsInfo.id && this.data.carts[i].option_id == optionsId) {
            this.setData({
              popNum: this.data.carts[i].total,
              popCard: this.data.carts[i],
            });
            break;
          }
          this.setData({
            popNum: 0,
            popCard: {},
          });
        }
      } else {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        this.setData({
          specid: goodsSpecs,
        });
      }
    },
    getMemberPrice(_optionsId) {
      if (!_optionsId) return;
      let specsVIPPrc = 0;
      this.setData({
        specsVIPPrc
      });
      let urlStr = app.getNetAddresss("goods.other-info.option-vpi-price");
      urlStr += "&option_id=" + _optionsId;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            specsVIPPrc = res.data.vip_price || null;
          } else {
            specsVIPPrc = null;
          }
          this.setData({
            specsVIPPrc
          });
        },
        fail: function (res) {
          specsVIPPrc = null;
          this.setData({
            specsVIPPrc
          });
        },
      });

    },
    close() {
      this.setData({
        show2: false,
      });
    },
  }
})